package aliyun.cx.admin.service.impl;

import aliyun.cx.admin.entity.ArticleTag;
import aliyun.cx.admin.entity.Tag;
import aliyun.cx.admin.mapper.ArticleTagMapper;
import aliyun.cx.admin.service.ArticleTagService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

@Service
public class ArticleTagServiceImpl extends ServiceImpl<ArticleTagMapper, ArticleTag> implements ArticleTagService {
    
    private static final Logger log = LoggerFactory.getLogger(ArticleTagServiceImpl.class);
    
    @Override
    public List<Tag> getTagsByArticleId(Long articleId) {
        return baseMapper.selectTagsByArticleId(articleId);
    }
    
    @Override
    public List<Long> getArticleIdsByTagId(Long tagId) {
        return baseMapper.selectArticleIdsByTagId(tagId);
    }
    
    @Override
    @Transactional
    public boolean setArticleTags(Long articleId, List<Long> tagIds) {
        try {
            // 先删除已有的关联
            deleteByArticleId(articleId);
            
            // 如果标签列表不为空，则添加新的关联
            if (tagIds != null && !tagIds.isEmpty()) {
                List<ArticleTag> articleTags = new ArrayList<>();
                for (Long tagId : tagIds) {
                    ArticleTag articleTag = new ArticleTag();
                    articleTag.setArticleId(articleId);
                    articleTag.setTagId(tagId);
                    articleTags.add(articleTag);
                }
                return saveBatch(articleTags);
            }
            return true;
        } catch (Exception e) {
            log.error("设置文章标签失败", e);
            return false;
        }
    }
    
    @Override
    public boolean deleteByArticleId(Long articleId) {
        return baseMapper.deleteByArticleId(articleId) >= 0;
    }
    
    @Override
    public boolean deleteByTagId(Long tagId) {
        return baseMapper.deleteByTagId(tagId) >= 0;
    }
    
    @Override
    public boolean isArticleTagExists(Long articleId, Long tagId) {
        QueryWrapper<ArticleTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", articleId)
                   .eq("tag_id", tagId);
        return count(queryWrapper) > 0;
    }
}